﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using Foundation.ExtensionMethods;

namespace Foundation.MarkupExtensions
{
    public class EnumRadioMenu : MenuGenerator
    {
        protected override ICollection<FrameworkElement> GenerateMenu()
        {
            var property = SourceObject.GetType().GetProperty(SourcePropertyName);
            var type = property.PropertyType;
            var value = SourceObject.GetPropertyValue(SourcePropertyName);
            var values = Enum.GetValues(type);
            var items =
               values.Cast<object>().Select(
                   v =>
                   new MenuItem
                   {
                       DataContext = v,
                       IsChecked = Equals(v, value),
                       IsEnabled = !Equals(v, value),
                       Header = Localizing.ProvideValue(Enum.GetName(type, v))
                   }).ToList();

            foreach (var menuItem in items)
            {
                menuItem.StaysOpenOnClick = true;
                menuItem.Click += (sender, args) =>
                {
                    var item = (MenuItem)sender;
                    if (item.IsChecked) return;
                    items.Where(i => i.IsChecked).ForEach(i => i.IsChecked = false);
                    items.Where(i => !i.IsEnabled).ForEach(i => i.IsEnabled = true);
                    item.IsChecked = true;
                    item.IsEnabled = false;
                    property.SetValue(SourceObject, item.DataContext, BindingFlags.Default, null, null, null);
                };
            }

            return items.Cast<FrameworkElement>().ToList();
        }
    }
}
